package com.zj.hw.purchase.login;

import com.zj.hw.purchase.constant.Constant;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.Year;
import java.util.List;
import java.util.Scanner;
import java.util.Set;

/**
 * @author zhangbo
 * @program: hw-purchase
 * @ClassName Login
 * @description: $
 * @date 2024-12-25 19:51:39
 */
@Slf4j
@Component
public class Login {

    //华为mate 70
    private static final String PROJECT_URL = "https://www.vmall.com/product/comdetail/index.html?prdId=10086763070835&sbomCode=2601010517907";


    @PostConstruct
    public void login() throws Exception {

        WebDriver driver = this.createWebDriver();

        this.chooseProject(driver);

        WebElement scrollEle = driver.findElement(By.cssSelector("#prd-botnav-rightbtn > div > div"));
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("arguments[0].scrollIntoView();", scrollEle);
        Thread.sleep(3000);
        scrollEle.click();
        log.info("Page title: " + driver.getTitle());

        Scanner sc = new Scanner(System.in);
        String str = new String();
        str = sc.nextLine();

        this.chooseProject(driver);

        do {
            boolean btnFlag = this.clickByBtn(driver);
            if (btnFlag) {
                // 处理点击购买后的情况
                boolean invokeBuy = this.invokeBuy(driver);
                if (invokeBuy) {
                    log.info("进入预付款页面啦！");
                    this.submitOrder(driver);
                }
            }
        } while (true);


    }

    private WebDriver createWebDriver() {
        log.info(">>>>>>>> 开始设置本地WebDriver <<<<<<<<");
        ChromeOptions options = new ChromeOptions();

        options.addArguments("disable-infobars");
//        options.addArguments("--headless");
        options.addArguments("--dns-prefetch-disable");
        options.addArguments("--no-referrers");
        options.addArguments("--disable-gpu");
        options.addArguments("--disable-audio");
        options.addArguments("--no-sandbox");
        options.addArguments("--ignore-certificate-errors");
        options.addArguments("--allow-insecure-localhost");

        // 设置chrome的页面Load机制
        options.setPageLoadStrategy(PageLoadStrategy.EAGER);

        // 设置驱动
        // 通过系统类型,获取chrome驱动位置
        String chromeDriver = "/usr/local/bin/chromedriver";
        System.setProperty("webdriver.chrome.driver", chromeDriver);
        // 无头模式
//        System.setProperty("java.awt.headless", "true");

        WebDriver driver = new ChromeDriver(options);
        driver.get("https://www.vmall.com/product/comdetail/index.html?prdId=10086989076790&cid=322971");
//        driver.get("https://www.vmall.com/product/comdetail/index.html?prdId=10086763070835&sbomCode=2601010517907");
        log.info("Page title: " + driver.getTitle());
        return driver;
    }

    private void chooseProject(WebDriver driver) throws Exception {
        log.info("准备点击选择项目");
        driver.findElement(By.cssSelector("#product_content_box > div > div:nth-child(5) > div > div.css-1dbjc4n.r-1pkz85s.r-151r267.r-1o5risz.r-16pv4up.r-1keljc5.r-fg2qkj.r-187g3x.r-16qzwuk.r-1pb60y0.r-7898gx.r-m8azki.r-gu0qjt.r-9aemit.r-13qz1uu.r-1g40b8q > div:nth-child(1) > div > div.css-1dbjc4n.r-18u37iz.r-1w6e6rj > div:nth-child(4) > div")).click();
        driver.findElement(By.cssSelector("#product_content_box > div > div:nth-child(5) > div > div.css-1dbjc4n.r-1pkz85s.r-151r267.r-1o5risz.r-16pv4up.r-1keljc5.r-fg2qkj.r-187g3x.r-16qzwuk.r-1pb60y0.r-7898gx.r-m8azki.r-gu0qjt.r-9aemit.r-13qz1uu.r-1g40b8q > div:nth-child(2) > div > div.css-1dbjc4n.r-18u37iz.r-1w6e6rj > div:nth-child(1) > div")).click();
        log.info("正在选择...");
        Thread.sleep(1000);
    }

    private void submitOrder(WebDriver driver) throws Exception {
        log.info("准备点击提交订单");
        boolean submitOrder = false;
        while (!submitOrder) {
            try {
                Set<String> windowHandles = driver.getWindowHandles();
                for (String windowHandle : windowHandles) {
                    if (!driver.getWindowHandle().equals(windowHandle)) {
                        Thread.sleep(20);
                        WebElement element = driver.findElement(By.cssSelector("#checkoutSubmit > span"));
                        JavascriptExecutor js = (JavascriptExecutor) driver;
                        js.executeScript("arguments[0].scrollIntoView();", element);
                        String text = element.getText();
                        log.info("点击提交订单按钮: {}", text);
                        break;
                    }

                }
//                JavascriptExecutor js = (JavascriptExecutor) driver;
//                js.executeScript("arguments[0].scrollIntoView();", element);
//                js.executeScript("if(typeof ec != 'undefined')ec.order.submit();");
//                #checkoutSubmit > span
//                js.executeScript("if(typeof ec != 'undefined')ec.order.submit();");
                submitOrder = true;
            } catch (Exception e) {
                log.info("没有点击提交订单按钮");
                submitOrder = false;
            }
            Thread.sleep(10000);
        }
    }

    private boolean checkPopExists(WebDriver driver) {
        try {
            driver.findElement(By.cssSelector("#show_risk_msg_box .box-ct .box-cc .box-content"));
            return true;
        } catch (Exception e) {
            log.info("没有弹窗.....");
            return false;
        }

    }


    private boolean invokeBuy(WebDriver driver) throws Exception {
        String iframeText = "";
        Set<String> windowHandles = driver.getWindowHandles();
        if (windowHandles.size() <= 1) {
            boolean queueFlag = this.checkIframeWindows(driver);
            if (queueFlag) {
                log.info("出现排队弹窗，开始处理");
                WebElement iframeEle = driver.findElement(By.cssSelector("#RushBuyQueue"));
                driver.switchTo().frame(iframeEle);
                iframeText = driver.findElement(By.cssSelector(".ecWeb-queue .queue-tips")).getText();
                if (Constant.TIPS_SET.contains(iframeText)) {
                    if ("排队中".equals(iframeText)) {
                        log.info("检查是否可以进行下单操作，排队状态：【{}】", iframeText);
                    } else if ("当前排队人数过多，是否继续排队等待？".equals(iframeText)) {
                        log.info("检查是否可以进行下单操作，排队状态：【{}】", iframeText);
                        try {
                            List<WebElement> waitBtnEleList = driver.findElements(By.cssSelector(".ecWeb-queue .queue-btn .btn-ok"));
                            for (WebElement ele : waitBtnEleList) {
                                if ("继续等待".equals(ele.getText())) {
                                    ele.click();
                                }
                            }
                        } catch (Exception ex) {
                            log.error("当前尝试下单失败，继续等待按钮不存在或当前不可点击");
                        }
                    } else {
                        log.error("检查是否可以进行下单操作，当前提醒内容：【{}】", iframeText);
                    }
                }
                // 跳出iframe
                driver.switchTo().defaultContent();
            }
            return false;
        } else {
            iframeText = "待提交订单";
            return true;
        }

    }

    private boolean checkIframeWindows(WebDriver driver) throws Exception {
        log.info("开始检查是否出现排队弹窗");
        boolean isExist = false;
        //循环几次防止还没加载出来
        for (int i = 0; i < 10; i++) {
            try {
                driver.findElement(By.cssSelector("#iframeBox #queueIframe"));
                isExist = true;
            } catch (Exception ex) {
                log.info("没有出现排队弹窗, i: {}", i);
                Thread.sleep(20);
            }
        }

        return isExist;
    }

    private boolean clickByBtn(WebDriver driver) {

        List<WebElement> elementList = driver.findElements(By.id("prd-botnav-rightbtn"));
        for (WebElement ele : elementList) {
            String text = ele.getText();
            JavascriptExecutor js = (JavascriptExecutor) driver;
            js.executeScript("arguments[0].scrollIntoView();", ele);
            if ("立即购买".equals(text)) {
                ele.click();
                return true;
            }
        }
        String text = driver.findElement(By.cssSelector("#prd-botnav-rightbtn-txt")).getText();
        log.info("当前尝试下单失败，立即下单按钮不存在或当前不可点击: 【{}】", text);
        return false;

    }

}
